package com.dpiinc.TechPage.api

import com.dpiinc.TechPage.UserManager
import com.dpiinc.TechPage.model.BaseEntity
import com.dpiinc.TechPage.model.EditNoteResult
import com.dpiinc.TechPage.model.jbean.BaseBean
import com.dpiinc.TechPage.room.bean.NoteEntity
import io.reactivex.Observable
import org.json.JSONArray

/**
 * 新建、编辑、删除笔记相关API
 * Created by X on 2018/7/27.
 */
class EditNoteApi {

    companion object {
        private const val OPERATION_ADD = 0
        private const val OPERATION_EDIT = 1
        private const val OPERATION_DELETE = 2

        fun create(): EditNoteApi = EditNoteApi()
    }

    //Json格式[“labId”,”labId”..]
    private fun getLabelIdString(note: NoteEntity): String {
        val jsonArray = JSONArray()
        note.label?.let { labelList ->
            labelList.forEach {
                jsonArray.put(it.id)
            }
        }
        return jsonArray.toString()
    }

    fun add(note: NoteEntity): Observable<BaseEntity<EditNoteResult>> {
        val params = HashMap<String, String>()
        params["uId"] = UserManager.getUserId()
        params["accessToken"] = UserManager.getAccessToken()
        params["noteOperate"] = OPERATION_ADD.toString()
        params["noteName"] = note.noteName ?: ""
        params["createTime"] = note.createTime.toString()
        params["editTime"] = note.modifyTime.toString()
        params["labelList"] = getLabelIdString(note)
        return RetrofitFactory.getInstance().editNote(params)
    }

    fun edit(note: NoteEntity): Observable<BaseEntity<EditNoteResult>> {
        val params = HashMap<String, String>()
        params["uId"] = UserManager.getUserId()
        params["accessToken"] = UserManager.getAccessToken()
        params["noteOperate"] = OPERATION_EDIT.toString()
        params["noteId"] = note.noteId
        params["noteName"] = note.noteName ?: ""
        params["createTime"] = note.createTime.toString()
        params["editTime"] = note.modifyTime.toString()
        params["labelList"] = getLabelIdString(note)
        return RetrofitFactory.getInstance().editNote(params)
    }

    fun delete(note: NoteEntity): Observable<BaseEntity<EditNoteResult>> {
        val params = HashMap<String, String>()
        params["uId"] = UserManager.getUserId()
        params["accessToken"] = UserManager.getAccessToken()
        params["noteOperate"] = OPERATION_DELETE.toString()
        params["noteId"] = note.noteId
        return RetrofitFactory.getInstance().editNote(params)
    }

    fun clear(note: NoteEntity): Observable<BaseEntity<BaseBean>>{
        val params = HashMap<String, String>()
        params["uId"] = UserManager.getUserId()
        params["accessToken"] = UserManager.getAccessToken()
        params["noteId"] = note.noteId
        return RetrofitFactory.getInstance().clearNote(params)
    }

}